import {designPage, reactive, useRefs} from "plain-design-composition";
import {DemoRow} from "../../Demo/DemoRow";
import {$message, Button, Form, FormItem, Input} from "../../../../packages";
import CloseOutlined from "@ant-design/icons/CloseOutlined";

export default designPage(() => {

  const { formData } = reactive({
    formData: {
      email: '111@aa.com',
      addressList: [
        { addr: '' }
      ],
    },
  });
  const { refs, onRef } = useRefs({ form: Form });

  async function save() {
    await refs.form!.validate();
    $message('校验通过');
  }

  return () => (
    <div>
      <DemoRow title={'动态增减表单项'}>
        <Form ref={onRef.form} modelValue={formData}>
          <FormItem label={'收件箱'} field={'email'} rules={{
            type: 'email',
            // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            // message: '请输入正确的邮箱',
            required: true,
            // trigger: 'blur',
          }}>
            <Input v-model={formData.email}/>
          </FormItem>
          {formData.addressList.map((item, index) => (
            <FormItem label={`收件人地址${index + 1}`} field={`addressList.${index}.addr`} key={index} rules={{
              required: true,
              // trigger: 'blur'
            }}>
              <div style={{ display: 'flex' }}>
                <Input v-model={item.addr}/>
                <Button icon={<CloseOutlined/>} style={{ marginLeft: '4px' }} onClick={() => {formData.addressList.splice(index, 1);}}/>
              </div>
            </FormItem>
          ))}
          <FormItem colon={false}>
            <Button label={'保存'} onClick={save}/>
            <Button label={'新增收件地址'} onClick={() => formData.addressList.push({ addr: '' })}/>
          </FormItem>
        </Form>
      </DemoRow>
    </div>
  );
});
